package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.listener.ExcelDictDtoListener;
import com.atguigu.srb.core.pojo.dto.ExcelDictDto;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author 熊磊
 * @since 2022-01-24
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Resource
    RedisTemplate redisTemplate;

    /**
     * 数据字典Excel导入
     * @param inputStream
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDto.class,new ExcelDictDtoListener(this.baseMapper)).sheet().doRead();
        log.info("Excel导入成功");
    }

    /**
     * 获取ExcelDictDto的列表
     * @return
     */
    @Override
    public List<ExcelDictDto> listDictData() {
        List<Dict> dictList = baseMapper.selectList(null);
        ArrayList<ExcelDictDto> result = new ArrayList<>();
        dictList.forEach((dict -> {
            ExcelDictDto excelDictDto = new ExcelDictDto();
            BeanUtils.copyProperties(dict,excelDictDto);
            result.add(excelDictDto);
        }));
        return result;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {
        // 判断redis中是否有数据
        try { // trycatch放止连接不上redis报错
            List<Dict> redisDictList = (List<Dict>) redisTemplate.opsForValue().get("srb.core:dictList" + parentId);
            if (redisDictList!=null){
                log.info("从redis中获取数据列表");
                return redisDictList;
            }
        } catch (Exception e) {
            log.error("redis服务器异常"+ ExceptionUtils.getStackTrace(e));
        }

        log.info("从数据库中获取数据列表");
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id",parentId);
        List<Dict> list = baseMapper.selectList(dictQueryWrapper);
        list.forEach(dict -> {
            dict.setHasChildren(hasChildren(dict.getId()));
        });

        try {
            // 将数据存入redis
            log.info("将数据存入redis");
            redisTemplate.opsForValue().set("srb.core:dictList" + parentId,list,5, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("redis服务器异常"+ ExceptionUtils.getStackTrace(e));
        }
        return list;
    }

    private boolean hasChildren(Long id){
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id",id);
        Long count = baseMapper.selectCount(dictQueryWrapper);
        return count>0;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {

        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(dictQueryWrapper);
        return this.listByParentId(dict.getId());
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {

        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("dict_code", dictCode);
        Dict parentDict = baseMapper.selectOne(dictQueryWrapper);

        if(parentDict == null){
            return "";
        }

        dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper
                .eq("parent_id", parentDict.getId())
                .eq("value", value);
        Dict dict = baseMapper.selectOne(dictQueryWrapper);

        if(dict == null){
            return "";
        }

        return dict.getName();
    }
}
